package com.guozcc.bootweb.util;


import com.guozcc.bootweb.platform.common.DateUtils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class Rsa {
    public static void main(String[] args) throws Exception {
        //createKey();
        String privateKeyStr = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAgv62zpx9/bNPdGND2yZ33bSwDleAu25L760Ac23wlC0w9uCEAB5eWjTyT2zhBDMsiICw/o56wQyhK4ZCiReU3wIDAQABAkA4yzJ69cJyQlHKhlcfJtiFWReTwEBiAvoNWhZ99UZ/F1GcsFxCb8R7A4nIBBArQTiKunl1+TiOiS/wZd38mxGxAiEAxEaLIITIH9rph5dTmDk+k16kbxHvKAAFkXNZbb3T5OMCIQCq2vMMftm0X1QF3oRs5D305nDqOGxgwdc743Dwz0qM1QIhAJqjQaYDN3DxlqA/d5stLsIJBOCFbrlDGx/3k3PE5ZclAiAje+Ochb/bKS0/Js6j+ucvNKjgzCUeF0QHSR5MtRCLnQIhALH/YKaa+I4NbWNT4HHdAmVC6U+LdvMKMgd91Xx/IISi";
        String publicKeyStr = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIL+ts6cff2zT3RjQ9smd920sA5XgLtuS++tAHNt8JQtMPbghAAeXlo08k9s4QQzLIiAsP6OesEMoSuGQokXlN8CAwEAAQ==";
        while (true){
            //signStr("测试申诉局啊实打实大啊实打实大师大撒啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊阿萨达啊实打实大师大师傅地方大刚发搭嘎苟富贵好家伙看没看黄金卡",publicKeyStr,privateKeyStr);
            signFile("D:\\install\\dataease-offline-installer-v2.1.0.tar.gz",publicKeyStr,privateKeyStr);
            System.out.println(DateUtils.getCurrentDateStr(null));
        }
    }

    public static void createKey() throws Exception {
        // 初始化密钥对生成器
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(512);

        // 生成密钥对
        KeyPair pair = keyGen.generateKeyPair();

        PrivateKey aPrivate = pair.getPrivate();
        PublicKey aPublic = pair.getPublic();
        String publicKeyStr = Base64.getEncoder().encodeToString(aPublic.getEncoded());
        String privateKeyStr = Base64.getEncoder().encodeToString(aPrivate.getEncoded());
        System.out.println("RSA::PrivateKey::" + privateKeyStr);
        System.out.println("RSA::PublicKey::" + publicKeyStr);
    }


    public static void signStr(String data, String publicKeyStr, String privateKeyStr) throws Exception {
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyStr);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(publicKeySpec);

        byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyStr);
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(pkcs8EncodedKeySpec);
        // 初始化签名对象
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        // 更新待签名的数据
        signature.update(data.getBytes());
        // 执行签名
        byte[] signed = signature.sign();
        // 输出签名结果
        System.out.println("sign: " + Base64.getEncoder().encodeToString(signed));
    }


    public static void signFile(String path, String publicKeyStr, String privateKeyStr)  {
        ByteArrayOutputStream baos = null;
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(path);
            baos = new ByteArrayOutputStream(fin.available());
            byte[] buf = new byte[1024*1024];
            int len ;
            while (( len = fin.read(buf))!=-1){
                baos.write(buf,0,len);
            }

        }catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                fin.close();
            }catch (IOException e){
                e.printStackTrace();
            }
            try {
                baos.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }


        //byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyStr);
        //X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
        //PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(publicKeySpec);

        try {
            byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyStr);
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(pkcs8EncodedKeySpec);
            // 初始化签名对象
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(privateKey);
            // 更新待签名的数据
            signature.update(baos.toByteArray());
            // 执行签名
            byte[] signed = signature.sign();


            // 输出签名结果
            System.out.println("sign: " + Base64.getEncoder().encodeToString(signed));
        } catch (SignatureException | InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException e){
            e.printStackTrace();
        }

    }
}
